import {app, shell, Tray, Menu, BrowserWindow, ipcMain} from 'electron'
import {join} from 'path'
import {electronApp, optimizer, is} from '@electron-toolkit/utils'
import icon from '../../resources/icon.ico?asset'

let appIcon = null;
function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        frame: false,
        width: 1340,
        height: 800,
        show: false,
        // transparent:true,
        autoHideMenuBar: true,
        icon: join(__dirname, '../../resources/icon.ico'), // 解决开发时图标替换
        ...(process.platform === 'linux' ? {icon} : {}),
        webPreferences: {
            contextIsolation: false,//禁用上下文隔离12版本以后默认就禁用了
            preload: join(__dirname, '../preload/index.js'),
            sandbox: false,
            nodeIntegration:true,//开启上下文隔离
            devTools: true,
            webSecurity: false,//允许跨域请求
        }
    })
    process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = true;
    mainWindow.on('ready-to-show', () => {
        mainWindow.show()
    })
    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url)
        return {action: 'deny'}
    })
    // HMR for renderer base on electron-vite cli.
    // Load the remote URL for development or the local html file for production.
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
        //启动的时候打开控制台  在下面打开
        mainWindow.webContents.openDevTools({mode: 'bottom'});
    } else {
        mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
    }
    appIcon = new Tray(join(__dirname, '../../resources/icon.ico'));
    var contextMenu = Menu.buildFromTemplate([{
        label: '最大化',
        type: 'normal',
        role: 'close',
        click: function (item, focusedWindow) {
            mainWindow.maximize();
            mainWindow.show();
        }
    },
        {
            label: '最小化',
            type: 'normal',
            role: 'minimize',
            click: function (item, focusedWindow) {
                mainWindow.hide();
            }
        },
        {
            label: '关于',
            type: 'normal',
            checked: true,
            click: function (item, focusedWindow) {
                shell.openExternal("https://gitee.com/yq5858588")
            }
        },
        {
            label: '兔子中医',
            type: 'normal',
            checked: true,
            click: function (item, focusedWindow) {
                shell.openExternal("https://space.bilibili.com/28324807")
            }
        },
        {label: '', type: 'separator'},
        {
            label: '退出',
            type: 'normal',
            role: 'close',
            click: function (item, focusedWindow) {
                app.quit();
            }
        }
    ]);
    appIcon.setToolTip('欢迎使用兔子中医-超人数据库');
    appIcon.setContextMenu(contextMenu);
    //单点击 1.主窗口显示隐藏切换 2.清除闪烁
    appIcon.on("click", function () {
        // if (!!timer) {
        // appIcon.setImage(path.join(appIcon, 'icon.ico'))
        //主窗口显示隐藏切换
        mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
        // }
    })
    ipcMain.on('sys_max', (event, args) => {
        let isMaximized = mainWindow.isMaximized();
        event.sender.send("isMaximized", isMaximized);
        if (isMaximized) {
            mainWindow.restore();
        } else {
            mainWindow.maximize();
        }
    })
    ipcMain.on('sys_mini', () => {
        mainWindow.minimize();
    })
    ipcMain.on('sys_close', () => {
        app.quit();
    })
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    // Set app user model id for windows
    electronApp.setAppUserModelId('com.electron')
    // Default open or close DevTools by F12 in development
    // and ignore CommandOrControl + R in production.
    // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
    app.on('browser-window-created', (_, window) => {
        optimizer.watchWindowShortcuts(window)
    })
    createWindow()
    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
    if (appIcon) appIcon.destroy();
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
